package android.test.devicetest;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.test.getintent.GetIntent;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.util.Log;

public class Bluetooth extends Activity {

    private static final String TAG = "BluetoothTestActivity";

    private BluetoothAdapter mAdapter;
    private BroadcastReceiver mBluetoothReceiver;
    private Handler mHandler;
    private TextView mResult;
    private int mTestCount;
    private int mTestOpen;
    private ProgressBar progressBar;
    boolean stop = false;
    private static final int MSG_OPEN = 0;
    private static final int MSG_FAILED = 1;
    private static final int MSG_FINISH_TEST = 2;
    private boolean isTestFinish = false;
    boolean checkOk = false;
    boolean trYes = true;
    private TextView mTextView;

    public Bluetooth() {
        this.mHandler = new MyHandler();
        this.mBluetoothReceiver = new MyBroadcastReceiver();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.bluetooth);

        mResult = (TextView) findViewById(R.id.resultText);
        progressBar = (ProgressBar) findViewById(R.id.progress);
        this.mAdapter = BluetoothAdapter.getDefaultAdapter();
        mTextView = (TextView) findViewById(R.id.tvDevices);
    }

    protected void onResume() {
        super.onResume();

        mTextView.setText(null);

        stop = false;
        if ((this.mAdapter != null)) {
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
            intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
            intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
            intentFilter.addAction(BluetoothDevice.ACTION_FOUND);

            registerReceiver(this.mBluetoothReceiver, intentFilter);
            if (this.mAdapter.isEnabled()) {
                mAdapter.startDiscovery();
                mResult.setText(getString(R.string.BluetoothScan));
            } else {
                this.mHandler.sendEmptyMessage(MSG_OPEN);
                mResult.setText(getString(R.string.BluetoothInit));
            }
        } else {
            // findViewById(R.id.btn_Pass).setVisibility(View.INVISIBLE);
            this.mResult.setText(getString(R.string.BluetoothAdapterFail));
            progressBar.setVisibility(View.INVISIBLE);
        }
    }

    public void onPause() {
        super.onPause();
        stop = true;
        if (this.mAdapter == null) {
            return;
        }
        unregisterReceiver(mBluetoothReceiver);
        mAdapter.cancelDiscovery();
        mHandler.removeMessages(MSG_FAILED);
    }

    class MyHandler extends Handler {
        public void handleMessage(Message msg) {
            if (stop) {
                return;
            }
            switch (msg.what) {
            case MSG_OPEN:
                Log.i(TAG, "142,mAdapter.isEnabled()" + mAdapter.isEnabled());
                if (mAdapter.isEnabled()) {
                    Log.i(TAG, "145,bluetooth is open and then startDiscovery!");
                    mAdapter.startDiscovery();
                    removeMessages(MSG_OPEN);
                } else {
                    if (mTestOpen < 15) {
                        Log.i(TAG, "bluetooth is close and then open it! mTestOpen=" + mTestOpen);
                        mTestOpen++;
                        mAdapter.enable();
                        sendEmptyMessageDelayed(MSG_OPEN, 1000L);
                    } else {
                        progressBar.setVisibility(View.INVISIBLE);
                        mResult.setText(getString(R.string.BluetoothOpenF));
                        failed();
                    }
                }
                break;
            case MSG_FAILED:
                // ((Button) findViewById(R.id.btn_Fail)).performClick();
                break;
            case MSG_FINISH_TEST:
                removeMessages(MSG_OPEN);
            }
        }
    }

    private void failed() {
        mHandler.removeMessages(MSG_FAILED);
        // mHandler.sendEmptyMessageAtTime(MSG_FAILED,
        // DeviceTest.TEST_FAILED_DELAY);
    }

    class MyBroadcastReceiver extends BroadcastReceiver {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (stop) {
                return;
            }
            if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
                int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
                        Integer.MIN_VALUE);
                if (state == BluetoothAdapter.STATE_ON) {
                    Log.i(TAG, "onReceive -- STATE_ON");
                    mAdapter.startDiscovery();
                } else if (state == BluetoothAdapter.STATE_OFF) {
                    Log.i(TAG, "onReceive -- STATE_OFF");
                }
            } else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_STARTED)) {
                Log.i(TAG, "onReceive -- ACTION_DISCOVERY_STARTED mTestCount="
                        + mTestCount);
                mResult.setText(getString(R.string.BluetoothScan));
            } else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {
                Log.i(TAG, "onReceive -- ACTION_DISCOVERY_FINISHED");
                if (isTestFinish) {
                    progressBar.setVisibility(View.INVISIBLE);
                    mResult.setText(getString(R.string.bluetooth_scan_finish));
                    return;
                }
                if (mTestCount < 1) {
                    mTestCount++;
                    mAdapter.startDiscovery();

                } else {
                    progressBar.setVisibility(View.INVISIBLE);
                    mResult.setText(getString(R.string.BluetoothFindF));

                    failed();
                }
            } else if (action.equals(BluetoothDevice.ACTION_FOUND)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (device != null) {
                    isTestFinish = true;

                    int deviceType = device.getBluetoothClass().getMajorDeviceClass();
                    String strDeviceType = null;
                    if (1024 == deviceType) {
                        strDeviceType = getString(R.string.bluetooth_earpiece);
                    } else if (512 == deviceType) {
                        strDeviceType = getString(R.string.bluetooth_cellphone);
                    } else if (1536 == deviceType) {
                        strDeviceType = getString(R.string.bluetooth_printer);
                    } else if (256 == deviceType) {
                        strDeviceType = getString(R.string.bluetooth_computer);
                    }

                    mTextView.append(String.format("%20s\t%26s\t%16s\n",
                        device.getName(), device.getAddress(), strDeviceType));

                    mHandler.sendEmptyMessageDelayed(MSG_FINISH_TEST, 0);
                }
            }
        }
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
        case KeyEvent.KEYCODE_BACK:
            finish();
            if (mAdapter != null) mAdapter.disable();
            System.exit(0);
            break;

        case KeyEvent.KEYCODE_ENTER:
            finish();
            if (mAdapter != null) mAdapter.disable();
            getIntents("status");
            break;

        case KeyEvent.KEYCODE_DPAD_LEFT:
            progressBar.setVisibility(View.INVISIBLE);
            mResult.setText(getString(R.string.bluetooth_scan_finish));
            stop = true;
            if (mAdapter != null) {
                mAdapter.cancelDiscovery();
            }
            break;

        case KeyEvent.KEYCODE_DPAD_RIGHT:
            progressBar.setVisibility(View.VISIBLE);
            mTextView.setText(null);
            stop = false;
            if (mAdapter != null) {
                if (mAdapter.isEnabled()) {
                    mAdapter.startDiscovery();
                    mResult.setText(getString(R.string.BluetoothScan));
                } else {
                    mHandler.sendEmptyMessage(MSG_OPEN);
                    mResult.setText(getString(R.string.BluetoothInit));
                }
            }
            break;
        }
        return super.onKeyUp(keyCode, event);
    }

    private void getIntents(String intent) {
        Intent mIntent = GetIntent.getItemIntent(Bluetooth.this, intent);
        if (mIntent != null) {
            startActivity(mIntent);
        }
    }

}
